<?php
//http://ywhblog.top/2021/06/06/
//https://blog.csdn.net/ice_mocha/article/details/116460057
include 'conn.php';	

require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
//$worksheet->setCellValue('A1', 'Welcome to Helloweba.');

//表头数组
$title = ['订单号', '样品/礼品', '收件人','手机号','地址','快递单号'];

//setCellValueByColumnAndRow(列位置,行位置,单元格的值)
 
foreach ($title as $key => $value) {
    $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
}

$row = 2; //从第二行开始

$sql = "SELECT * FROM sectors";
$rs =  mysqli_query($con,$sql);
while($item = $rs->fetch_assoc()){
 
    $column = 1; //列从第一格开始
    foreach ($item  as $value) {
        $worksheet->setCellValueByColumnAndRow($column, $row, $value);
        $column++;
    }
    $row++;  //每一列填充完，+1

} 


// $writer = new Xlsx($spreadsheet);
// $writer->save('hello2.xlsx');

//文件名
$fileName = 'temp';
//文件类型
$fileType = 'Xlsx';

//1.下载到服务器
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($fileName.'.'.$fileType);

$result = array();
$result["message"] ="OK";	
$result["success"] =true;
$result["path"] ="controller/temp.Xlsx";
echo json_encode($result);

//2.输出到浏览器
// $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件
// excelBrowserExport($fileName, $fileType);
// $writer->save('php://output');


// function excelBrowserExport($fileName, $fileType) {
//     //文件名称校验
//     if(!$fileName) {
//         trigger_error('文件名不能为空', E_USER_ERROR);
//     }

//     //Excel文件类型校验
//     $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
//     if(!in_array($fileType, $type)) {
//         trigger_error('未知文件类型', E_USER_ERROR);
//     }

//     if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
//         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//         header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
//         header('Cache-Control: max-age=0');
//     } else { //Excel5
//         header('Content-Type: application/vnd.ms-excel');
//         header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
//         header('Cache-Control: max-age=0');
//     }
// }
?>